package cn.school.teacher.evaluation.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.school.common.utils.StringUtils;
import cn.school.common.utils.SysUserUtils;
import cn.school.sys.dao.SysUserDao;
import cn.school.sys.dao.TermTimeDao;
import cn.school.sys.entity.SysUser;
import cn.school.teacher.evaluation.dao.TeacherEvaluationTaskDao;
import cn.school.teacher.evaluation.dao.TeacherEvaluationUserTaskDao;
import cn.school.teacher.evaluation.dto.UserDto;
import cn.school.teacher.evaluation.entity.TeacherEvaluationTask;
import cn.school.teacher.evaluation.entity.TeacherEvaluationUserTask;
import cn.school.teacher.evaluation.service.EvaluationTaskService;
import cn.school.teacher.evaluation.vo.req.TeacherEvaluationTaskReqVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("EvaluationTaskService")
public class EvaluationTaskServiceImpl extends ServiceImpl<TeacherEvaluationTaskDao, TeacherEvaluationTask> implements EvaluationTaskService {
	
	@Autowired
	private TeacherEvaluationUserTaskDao teacherEvaluationUserTaskDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private TermTimeDao termTimeDao;
	
	
	@Override
	public IPage<TeacherEvaluationTask> getPage(Map<String, Object> params) {
		
		QueryWrapper<TeacherEvaluationTask> wrapper = new QueryWrapper();
		
		int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
		int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));
		
		
		// =========== 考评阶段 =================
		String tetaStageType = (String) params.get("queryStageType"); // 考评阶段
		String acyeId = (String) params.get("queryStageAcyeId"); // 学年
		String tetiId = (String) params.get("queryStageTetiId"); // 学期
		String tetaMonth = (String) params.get("queryStageMonth"); // 月份
		if (StrUtil.isNotEmpty(tetaStageType)) {
			short tetaStageTypeValue = Short.valueOf(tetaStageType);
			if (tetaStageTypeValue != 0) {
				wrapper.eq("teta.teta_stage_type", Short.valueOf(tetaStageType));
				if (StrUtil.isNotEmpty(acyeId)) {
					wrapper.eq("teta.acye_id", Long.valueOf(acyeId));
				}
			}
			
			if (tetaStageTypeValue == 2 && StrUtil.isNotEmpty(acyeId) && StrUtil.isNotEmpty(tetiId)) {
				wrapper.eq("teta.teti_id", Long.valueOf(tetiId));
			} else if (tetaStageTypeValue == 3 && StrUtil.isNotEmpty(acyeId) && StrUtil.isNotEmpty(tetaMonth)) {
				wrapper.eq("teta.teta_month", Long.valueOf(tetaMonth));
			}
			
		}
		
		
		String tetaCoverUserId = (String) params.get("tetaCoverUserId"); // 受评人Id
		if (StrUtil.isNotEmpty(tetaCoverUserId)) {
			wrapper.eq("teta.teta_cover_user_id", tetaCoverUserId);
		}
		
		// 开始时间， 结束时间
		String beginTime = (String) params.get("beginTime");
		String endTime = (String) params.get("endTime");
		if (StrUtil.isNotEmpty(beginTime)) {
			wrapper.gt("teta.create_time", beginTime);
		}
		if (StringUtils.isNotEmpty(endTime)) {
			wrapper.lt("teta.create_time", endTime);
		}
		
		
		String tetaName = (String) params.get("taskName");// 任务名称
		if (StringUtils.isNotEmpty(tetaName)) {
			wrapper.like("teta.teta_name", tetaName);
		}
		//	租户
		wrapper.eq("teta.tenant_id", SysUserUtils.getSysUser().getTenantId());
		wrapper.orderByDesc("teta.create_time");
		
		IPage<TeacherEvaluationTask> page = new Page<TeacherEvaluationTask>(pageNum, pageSize);
		List<TeacherEvaluationTask> dtoList = this.baseMapper.getListBySql(page, wrapper);

//        if (dtoList != null && dtoList.size() != 0) {
//
//            // 任务发起者ID获取
//            List<Long> userIdList = dtoList.stream().map(TeacherEvaluationTask::getUserId).collect(Collectors.toList());
//
//            // 任务发起人 ：用户数据获取
//            LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
//            userWrapper.in(SysUser::getId, userIdList);
//            List<SysUser> sysUsers = this.sysUserDao.selectList(userWrapper);
//            Map<Long, SysUser> userMap = new HashMap<>();
//            if (sysUsers != null) {
//                userMap = sysUsers.stream().collect(Collectors.toMap(item1 -> item1.getId(), a -> a, (k1, k2) -> k1));
//            }
//
//            for (TeacherEvaluationTask dto : dtoList) {
//                // 发起人名称
//                if (userMap.containsKey(dto.getUserId())) {
//                    dto.setUserName(userMap.get(dto.getUserId()).getUsername());
//                }
//            }
//        }
		page.setRecords(dtoList);
		return page;
	}
	
	@Override
	@Transactional
	public int create(TeacherEvaluationTaskReqVo teacherEvaluationTaskVo) {
		TeacherEvaluationTask teacherEvaluationTask = new TeacherEvaluationTask();
		BeanUtils.copyProperties(teacherEvaluationTaskVo, teacherEvaluationTask);
		// 插入主任务
		int count = this.baseMapper.insert(teacherEvaluationTask);
		if (StringUtils.isNotEmpty(teacherEvaluationTaskVo.getTaskScoreUserIds())) {
			// 插入子任务数据
			Iterator<String> iterator = Arrays.asList(teacherEvaluationTaskVo.getTaskScoreUserIds().split(",")).iterator();
			TeacherEvaluationUserTask teacherEvaluationUserTask = null;
			while (iterator.hasNext()) {
				Long scoreUserId = Long.parseLong(iterator.next());
				teacherEvaluationUserTask = new TeacherEvaluationUserTask();
				BeanUtils.copyProperties(teacherEvaluationTaskVo, teacherEvaluationUserTask);
				teacherEvaluationUserTask.setUserId(scoreUserId);
				teacherEvaluationUserTask.setTetaId(teacherEvaluationTask.getId());
				teacherEvaluationUserTask.setTeutStatus((short) 0);
				this.teacherEvaluationUserTaskDao.insert(teacherEvaluationUserTask);
			}
		}
		return count;
	}
	
	@Override
	@Transactional
	public int deleteByIds(Long[] ids) {
		int count = 0;
		if (ids != null && ids.length != 0) {
			List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
			idList.forEach(tmpId -> {
				LambdaQueryWrapper<TeacherEvaluationUserTask> lambdaQueryWrapper = new LambdaQueryWrapper<>();
				lambdaQueryWrapper.eq(TeacherEvaluationUserTask::getTetaId, tmpId);
				this.teacherEvaluationUserTaskDao.delete(lambdaQueryWrapper);
			});
			count = this.baseMapper.deleteBatchIds(idList);
		}
		return count;
	}
	
	@Override
	public TeacherEvaluationTask getById(Long id) {
		TeacherEvaluationTask task = this.baseMapper.selectById(id);
		
		return task;
	}
	
	@Override
	public int update(Long id, TeacherEvaluationTask teacherEvaluationTask) {
		int count = this.baseMapper.updateById(teacherEvaluationTask);
		return count;
	}
	
	@Override
	public IPage<UserDto> getPageByUser(Map<String, Object> params) {
		QueryWrapper<UserDto> wrapper = new QueryWrapper();
		
		int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
		int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));
		
		String queryType = (String) params.get("queryType");
		String userName = (String) params.get("userName");
		String sydeName = (String) params.get("sydeName");
		String tenantId = "";
		if(Objects.nonNull(SysUserUtils.getSysUser()) && StringUtils.isNotEmpty(SysUserUtils.getSysUser().getUsername())){
			tenantId = SysUserUtils.getSysUser().getTenantId();
		}
		if(Objects.nonNull(SysUserUtils.getStudentUser()) && StringUtils.isNotEmpty(SysUserUtils.getStudentUser().getStudentId())){
			tenantId = SysUserUtils.getStudentUser().getTenantId();
		}
		if(Objects.nonNull(SysUserUtils.getParentUser()) && StringUtils.isNotEmpty(SysUserUtils.getParentUser().getStudentId())){
			tenantId = SysUserUtils.getParentUser().getTenantId();
		}
		wrapper.eq(StringUtils.isNotEmpty(tenantId), "syro.tenant_id", tenantId);
		
		if (StringUtils.isNotEmpty(userName)) {
			wrapper.like("sysu_name", userName);
		}
		if (StringUtils.isNotEmpty(sydeName)) {
			wrapper.like("syde.name", sydeName);
		}
		
		IPage<UserDto> page = new Page<UserDto>(pageNum, pageSize);
		List<UserDto> dtoList = "classTeacher".equals(queryType) ?
				this.sysUserDao.getClassTeacherListBySearch(page, wrapper) :
				this.sysUserDao.getEmployeListBySearch(page, wrapper);
		page.setRecords(dtoList);
		return page;
	}

    @Override
    public IPage<UserDto> getPageByUserAndName(Map<String, Object> params) {
		QueryWrapper<UserDto> wrapper = new QueryWrapper();

		int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
		int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));

		String queryType = (String) params.get("queryType");
		String userName = (String) params.get("userName");
		String tenantId = "";
		if(Objects.nonNull(SysUserUtils.getSysUser()) && StringUtils.isNotEmpty(SysUserUtils.getSysUser().getUsername())){
			tenantId = SysUserUtils.getSysUser().getTenantId();
		}
		if(Objects.nonNull(SysUserUtils.getStudentUser()) && StringUtils.isNotEmpty(SysUserUtils.getStudentUser().getStudentId())){
			tenantId = SysUserUtils.getStudentUser().getTenantId();
		}
		if(Objects.nonNull(SysUserUtils.getParentUser()) && StringUtils.isNotEmpty(SysUserUtils.getParentUser().getStudentId())){
			tenantId = SysUserUtils.getParentUser().getTenantId();
		}
		wrapper.eq(StringUtils.isNotEmpty(tenantId), "syro.tenant_id", tenantId);
		if (StringUtils.isNotEmpty(userName)) {
			wrapper.like("sysu_name", userName);
		}

		String name = "班主任";
		IPage<UserDto> page = new Page<UserDto>(pageNum, pageSize);
		List<UserDto> dtoList = "classTeacher".equals(queryType) ?
				this.sysUserDao.getClassTeacherListBySearchAndName(page, wrapper, name) :
				this.sysUserDao.getEmployeListBySearchAndName(page, wrapper, name);
		page.setRecords(dtoList);
		return page;
    }

    @Override
	public List<UserDto> getSocreUserListByEvtaId(Long id) {
		QueryWrapper<TeacherEvaluationUserTask> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("teua.teta_id", id);
		List<UserDto> list = teacherEvaluationUserTaskDao.getSoreUserList(queryWrapper);
		if (list != null && list.size() != 0) {
			list.removeAll(Collections.singleton(null));
		}
		return list;
	}
	
	@Override
	public UserDto getTetaCoverUserByUserId(Long id) {
		SysUser sysUser = this.sysUserDao.selectById(id);
		UserDto userDto = new UserDto();
		if (sysUser != null) {
			userDto.setId(sysUser.getId());
			userDto.setUserName(sysUser.getUsername());
		}
		return userDto;
	}
	
	@Override
	public List<TeacherEvaluationTask> getTeEvTaskListByNotProcess() {
		LambdaQueryWrapper<TeacherEvaluationTask> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TeacherEvaluationTask::getTetaStatus, 0);
		queryWrapper.eq(TeacherEvaluationTask::getTenantId, SysUserUtils.getSysUser().getTenantId());
		return this.baseMapper.selectList(queryWrapper);
	}
}
